<?php

namespace app\common\service\WebSocket;

use OSS\Model\ObjectInfo;
use app\Normal;
use app\BaseService;
class WebSocketTask extends BaseService
{
    CONST HOST = '0.0.0.0';
    CONST POST = 8002;

    protected $service;  //服务器对象

    public function start()
    {
        $this->service = new \Swoole\WebSocket\Server(self::HOST,self::POST);
        $this->service->set([
            'worker_num'        =>  \swoole_cpu_num(),
            'task_worker_num'   =>  30    //配置此参数后将会启用task功能
        ]);
        $this->service->on('open',[$this,'onOpen']);
        $this->service->on('message',[$this,'onMessage']);
        $this->service->on('task',[$this,'onTask']);  //使用task任务必须要注册task、finish回调函数
        $this->service->on('finish',[$this,'onFinish']);
        $this->service->on('close',[$this,'onClose']);
        $this->service->start();
    }

    /**
     * 建立连接
     * @param ObjectInfo $server
     * @param ObjectInfo $request
     */
    public function onOpen($server, $request)
    {
        global $host;
        $host = $request->header['host'] ??'';
        //$server->push($request->fd,json_encode(Normal::returnCode(Normal::SUC,"连接成功"),JSON_UNESCAPED_UNICODE));
    }

    /**
     * 收取客户端发包数据
     * @param ObjectInfo $server
     * @param ObjectInfo $frame
     */
    public function onMessage($server, $frame)
    {
        global $host;
        $data = [
            'data'  => base64_encode(rawurlencode($frame->data)),
            'fd'    => $frame->fd,
            'host'  => $host
        ];
//        $server->push($frame->fd,json_encode(Normal::returnCode(Normal::SUC,"连接成功",$data),JSON_UNESCAPED_UNICODE));
        $server->task($data);
    }

    /**
     * 开启异步队列任务处理池功能
     * @param ObjectInfo $server
     * @param int $taskId
     * @param int $workId
     * @param mixed $data
     */
    public function onTask($server,$taskId,$workId,$data)
    {
        $data = [
            'data'    => @json_decode(rawurldecode(base64_decode($data['data'])),true),
            'fd'      => $data['fd'],
            'host'    => $data['host']
        ];
        WebSocketService::instance()->runSocketService($server,$data);
    }

    /**
     * 队列处理完成回调方法
     * @param ObjectInfo $server
     * @param int $taskId
     * @param mixed $data
     */
    public function onFinish($server,$taskId,$data)
    {
    }

    /**
     * 连接关闭
     * @param ObjectInfo $server
     * @param int $fd
     */
    public function onClose($server,$fd)
    {
        echo "client {$fd} closed\n";
    }
}